#include "xmlimportdialog.h"

XMLImportDialog::XMLImportDialog()
{
setupUi(this);
setup_data();

QPushButton * okButton = qobject_cast<QPushButton *>( buttonBox->button( QDialogButtonBox::Ok ) );
    if (okButton != NULL)
    {
    okButton->setDisabled(true);
    }

QObject::connect( tableView,
                  SIGNAL( clicked(QModelIndex) ),
                  this,
                  SLOT( select_album(QModelIndex) ) );
QObject::connect( toolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( file_name() ) );                 
QObject::connect( sheetsPushButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( search_sheets() ) );
QObject::connect( sheetComboBox,
                  SIGNAL( activated(QString) ),
                  this,
                  SLOT( select_sheet(QString) ) );
QObject::connect( sheetComboBox,
                  SIGNAL( editTextChanged(QString) ),
                  this,
                  SLOT( select_sheet(QString) ) );

sheetComboBox->clearEditText();                  
}

XMLImportDialog::~XMLImportDialog()
{
}

void XMLImportDialog::closeEvent(QCloseEvent * e)
{
delete_model();
e->accept();
}

void XMLImportDialog::delete_model()
{
QSqlTableModel * old_model = qobject_cast<QSqlTableModel *>(tableView->model());
tableView->setModel(new QSqlTableModel);    
    if (NULL != old_model)
    {
    old_model->clear();
    }
delete old_model;
old_model = NULL;
return;
}

void XMLImportDialog::select_album(QModelIndex index)
{
QSqlTableModel * model = qobject_cast<QSqlTableModel *>(tableView->model());
QSqlRecord record = model->record( index.row() );
m["alb_table"] = record.value("table_name").toString();
m["alb_table_num"] = record.value("album_num").toString();
m["alb_table_name"] = record.value("album_name").toString();
QString num_bold = QLatin1String("<b>");
num_bold.append( m.value("alb_table_num") );
num_bold.append( QLatin1String("</b>") );
albumLabel->setText(num_bold);
check_selection();
}

QMap<QString, QString> XMLImportDialog::return_selected()
{

bool ready = true;
    if ( m.value("alb_table").isEmpty() )
    {
    ready = false;
    }

    if ( m.value("file_path").isEmpty() )
    {
    ready = false;
    }

    if ( m.value("file_sheet").isEmpty() )
    {
    ready = false;
    }

    if ( true == formatCheckBox->isChecked() )
    {
    m["ncat_export"] = QLatin1String("TRUE");
    }

    if ( true != ready )
    {
    QMessageBox::information( this,
                              tr("Information"),
                              tr("Select MS XML Spreadsheet file,\nworksheet and collection.") );
    m["not_ready"] = QLatin1String("TRUE");
    }

return m;
}

void XMLImportDialog::file_name()
{
QString path = QFileDialog::getOpenFileName( this,
                                             tr("Select XML file"),
                                             QString(""),
                                             tr("MS XML Spreadsheet Files (*.xml);;All Files (*)"));

    if ( true == path.isEmpty() )
    {
    fileLine->clear();
    sheetComboBox->setDisabled(true);
    sheetsPushButton->setDisabled(true);
    return;
    }

m["file_path"] = path;
QFile file(path);
sheetComboBox->clear();
sheetComboBox->clearEditText();
m["file_sheet"] = QLatin1String("");

    if ( true == file.open( QFile::ReadOnly | QFile::Text ) )
    {
    fileLine->setText( QDir::toNativeSeparators(path) );
    sheetComboBox->setDisabled(false);
    sheetsPushButton->setDisabled(false);
    }
    else
    {
    m["file_path"] = QLatin1String("");
    fileLine->clear();
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Could not open file.") );
    sheetComboBox->clearEditText();    
    sheetComboBox->clear();
    sheetComboBox->setDisabled(true);
    sheetsPushButton->setDisabled(true);
    }

file.close();
check_selection();
}

void XMLImportDialog::select_sheet( QString item )
{
m["file_sheet"] = item;
check_selection();
}

void XMLImportDialog::search_sheets()
{
QString path = m.value("file_path");
QString message = tr("Reading MS XML Spreadsheet File");
QSplashScreen * splash = new QSplashScreen( create_splash_image() );
splash->show();
qApp->processEvents();

    if ( true != path.isEmpty() )
    {
    XMLFile handler;
    QXmlSimpleReader reader;
    reader.setContentHandler(&handler);
    reader.setErrorHandler(&handler);

    QFile file(path);
        if ( true != file.open( QFile::ReadOnly | QFile::Text ) )
        {
        QMessageBox::critical( this,
                               tr("Error"),
                               tr("Could not open file.") );
        fileLine->clear();
        m["file_path"] = QLatin1String("");
        m["file_sheet"] = QLatin1String("");
        sheetComboBox->clear();
        sheetComboBox->clearEditText();
        sheetComboBox->setDisabled(true);
        sheetsPushButton->setDisabled(true);
        file.close();
        splash->close();
        delete splash;
        return;
        }
    
    splash->showMessage(message);
    qApp->processEvents();

    QXmlInputSource * xmlInputSource = new QXmlInputSource(&file);

    QStringList l;
        if ( reader.parse( xmlInputSource, false ) )
        {
        l = handler.return_data();
        }
        else
        {
        QString error = handler.errorString();
        QMessageBox::critical( this,
                               tr("Error"),
                               error  );
        splash->close();
        delete splash;
        return;
        }

    file.close();
    sheetComboBox->clear();
    sheetComboBox->clearEditText();
    sheetComboBox->addItems(l);
    delete xmlInputSource;
    xmlInputSource = NULL;
    }

splash->close();
delete splash;                            

check_selection();
}

void XMLImportDialog::check_selection()
{
m["file_sheet"] = sheetComboBox->currentText();
QPushButton * okButton = qobject_cast<QPushButton *>( buttonBox->button( QDialogButtonBox::Ok ) );
    if ( true != m.value("file_path").isEmpty() &&
         true != m.value("file_sheet").isEmpty() &&
         true != m.value("alb_table").isEmpty() )
    {
        if (okButton != NULL)
        {
        okButton->setDisabled(false);
        }
    }
}

QPixmap XMLImportDialog::create_splash_image()
{
QPixmap p;
bool found_in_cache = false;
QString cached_splash = QLatin1String("splash_image");
found_in_cache = QPixmapCache::find(cached_splash, p);
    if ( true != found_in_cache )
    {
    QString path = QCoreApplication::applicationDirPath();
    path.append ( QDir::separator() );
    path.append( QLatin1String("splash_image.png") );
    QFile f(path);
    bool ok = false;
    ok = f.open(QIODevice::ReadOnly);
        if ( true != ok )
        {
        qApp->processEvents();
        p = QPixmap(":/binary/empty_splash.png");
        return p;
        }
    p = QPixmap(path);
        if ( true == p.isNull() )
        {
        p = QPixmap(":/binary/empty_splash.png");
        }
    QPixmapCache::insert(cached_splash, p);
    }
return p;
}

void XMLImportDialog::setup_data()
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( !db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error" ),
                          tr("Database is closed.") );
    return;
    }

QSqlTableModel * model = new QSqlTableModel(0, db);
model->setTable("albums_reg");
    if (model->lastError().type() != QSqlError::NoError)
    {
    QMessageBox::warning(this,
                         tr("Error"),
                         model->lastError().text() );
    return;
    }

model->select();
model->setHeaderData(2, Qt::Horizontal, tr("Collection") );
model->setHeaderData(3, Qt::Horizontal, tr("Name") );
    if (model->lastError().type() != QSqlError::NoError)
    {
    QMessageBox::warning( this,
                          tr("Warning"),
                          model->lastError().text() );
    }

tableView->setModel(model);
tableView->setColumnWidth(3, 120);
tableView->hideColumn(0);
tableView->hideColumn(1);
tableView->hideColumn(4);
}
